<script setup lang="ts">
  import { onMounted, PropType, ref } from 'vue'
  import { getOrderGoodsDetail } from '@/api/order'
  import _ from 'lodash'
  import handleClipboard from '@/utils/clipboard'
  import { useQueryCodeForUpdateGood, useUpdateGoodSncode } from '@/services/pages/order/useOrder'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import CreateCodeModal from '@/views/code/list/components/create-code-modal/Index.vue'

  defineOptions({
    name: 'OrderDetailGoodList',
  })

  const { snCodeInfoForUpdateCode, querySnCode, queryLoading, resetQuery, queryCode } =
    useQueryCodeForUpdateGood()
  const { updateLoading, updateForm, update, resetForm } = useUpdateGoodSncode()

  const props = defineProps({
    orderDetail: {
      type: Object as PropType<OrderDetail>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 正在更新的商品的资产码
  const updatingProductRegisterCode = ref('')

  const updateProductDrawerVisible = ref(false)
  const updatingProduct = ref<OrderDetailAPIResponse.GoodListItem | null>(null)
  const goodListTotal = ref(0)
  const getGoodListPagination = ref({
    limit: 4,
    page: 1,
  })
  const goodList = ref<Array<OrderDetailAPIResponse.GoodListItem>>([])
  const createCodeModalVisible = ref(false)
  const createCodeModalInstance = ref<InstanceType<typeof CreateCodeModal> | null>(null)

  const getGoodList = async () => {
    const res = await getOrderGoodsDetail(props.orderDetail.id, getGoodListPagination.value)
    goodList.value = res.data.data?.rows
    goodListTotal.value = Number(res.data.data.total)
  }

  // 展示弹窗
  const showDrawer = (val: OrderDetailAPIResponse.GoodListItem) => {
    updateProductDrawerVisible.value = true
    updatingProduct.value = _.cloneDeep(val)
    workGoodsBindSnCodeVo.value.workGoodsId = val.id
    snCodes.value = val.codes ? val.codes.map((item) => item.securityCode).join('，') : ''
    updatingProductRegisterCode.value = val.codes
      ? val.codes.map((item) => item.registerCode).join('，')
      : ''
  }
  const snCodes = ref('')
  const workGoodsBindSnCodeVo = ref({
    snCodes: [],
    workGoodsId: '',
  })
  const changeLoading = ref(false)

  /**
   * 保存事件
   */
  const onSave = async () => {
    if (updateForm.value.snCodes.length === 0) {
      return
    }

    try {
      const res = await update(props.orderDetail.id)
      if (res.code === 20000) {
        HMessage.success('更新完成')
        hideUpdateGoodDrawer()
        resetQuery()
        getGoodList()
        emits('update')
        return
      }
      HMessageBox.error(res.message)
    } catch (error) {
      HMessageBox.error('更新失败，请稍后重试')
    }
  }

  /**
   * 条码查询事件
   */
  const onQuerySnCode = async () => {
    const errMsg = await queryCode()
    if (errMsg) {
      HMessageBox.error('查无此条码')
      return
    }

    if (!snCodeInfoForUpdateCode.value) {
      return
    }

    if (
      snCodeInfoForUpdateCode.value.register &&
      snCodeInfoForUpdateCode.value.register.userId !== props.orderDetail.userId
    ) {
      HMessageBox.error('两个条码绑定的用户不一致，禁止更换')
      return
    }

    if (updatingProduct.value) {
      updatingProductRegisterCode.value = snCodeInfoForUpdateCode.value.registerCode || ''
      updateForm.value = {
        snCodes: [snCodeInfoForUpdateCode.value.securityCode],
        workGoodsId: updatingProduct.value.id,
      }
      updatingProductRegisterCode.value = snCodeInfoForUpdateCode.value.registerCode || ''
      Object.assign(updatingProduct.value, {
        address: snCodeInfoForUpdateCode.value.register
          ? snCodeInfoForUpdateCode.value.register.address
          : '',
        area: snCodeInfoForUpdateCode.value.register
          ? snCodeInfoForUpdateCode.value.register.area
          : '',
        buyTime: snCodeInfoForUpdateCode.value.warrantyStartTime,
        city: snCodeInfoForUpdateCode.value.register
          ? snCodeInfoForUpdateCode.value.register.city
          : '',
        codes: [snCodeInfoForUpdateCode.value.securityCode],
        endTime: snCodeInfoForUpdateCode.value.warrantyEndTime,
        goodsBrand: snCodeInfoForUpdateCode.value.zjProduct.brand,
        goodsBrandId: snCodeInfoForUpdateCode.value.zjProduct.brandId,
        goodsId: snCodeInfoForUpdateCode.value.id,
        goodsModel: snCodeInfoForUpdateCode.value.zjProduct.model,
        goodsName: snCodeInfoForUpdateCode.value.zjProduct.name,
        goodsSpec: snCodeInfoForUpdateCode.value.spec.name,
        goodsSpecId: snCodeInfoForUpdateCode.value.spec.id,
        province: snCodeInfoForUpdateCode.value.register
          ? snCodeInfoForUpdateCode.value.register.province
          : '',
        qty: 1,
        town: snCodeInfoForUpdateCode.value.register
          ? snCodeInfoForUpdateCode.value.register.town
          : '',
        userName: snCodeInfoForUpdateCode.value.register
          ? snCodeInfoForUpdateCode.value.register.name
          : '',
        userPhone: snCodeInfoForUpdateCode.value.register
          ? snCodeInfoForUpdateCode.value.register.phone
          : '',
        snCodeStatus: 1,
        goodsCode: snCodeInfoForUpdateCode.value.zjProduct.itemNumber,
        saleModels: snCodeInfoForUpdateCode.value.zjProduct.saleModels,
      })
    }

    snCodes.value = snCodeInfoForUpdateCode.value.securityCode
  }

  const hideUpdateGoodDrawer = () => {
    resetForm()
    querySnCode.value = ''
    updateProductDrawerVisible.value = false
  }

  onMounted(() => {
    getGoodList()
  })

  defineExpose({
    goodList,
  })
</script>

<template>
  <div class="order-detail-good-list">
    <div class="title">产品信息({{ goodListTotal }})</div>
    <div class="table">
      <el-table :border="true" :data="goodList" resizable stripe style="width: 100%">
        <!-- 序号 -->
        <el-table-column label="序号" width="50" fixed="left" :align="'center'" type="index" />

        <!-- 条码 -->
        <el-table-column prop="codes" label="条码" width="180">
          <template #default="i">
            <span
              v-if="i.row.codes && i.row.codes.length > 0"
              style="display: flex; align-items: center; column-gap: 4px"
            >
              <ShowTooltip
                style="width: calc(100% - 30px)"
                placement="top"
                ref-name="testName"
                class-name="is_textClass"
                :content="i.row.codes.map((item) => item.securityCode).join(',') || ''"
                :is-text="true"
                color="#606266"
                :size="12"
                :offset="8"
                :show-after="200"
              />
              <HLink
                :data-clipboard-text="i.row.codes.map((item) => item.securityCode).join(',')"
                @click="
                  handleClipboard(i.row.codes.map((item) => item.securityCode).join(','), $event)
                "
              >
                复制
              </HLink>
            </span>
          </template>
        </el-table-column>

        <!-- 资产码 -->
        <el-table-column prop="registerCode" show-overflow-tooltip label="资产码">
          <template #default="{ row }">
            {{ (row.codes || []).map((item) => item.registerCode).join(', ') }}
          </template>
        </el-table-column>

        <!-- 产品编号 -->
        <el-table-column prop="goodsCode" show-overflow-tooltip label="产品编号" />

        <!-- 销售型号 -->
        <el-table-column prop="saleModels" show-overflow-tooltip label="销售型号" />

        <!-- 产品名称 -->
        <el-table-column prop="goodsName" show-overflow-tooltip label="产品名称" />

        <!-- 规格 -->
        <el-table-column prop="goodsSpec" show-overflow-tooltip label="规格" />

        <!-- 数量 -->
        <el-table-column prop="qty" label="数量" width="60" />

        <!-- 购买时间 -->
        <el-table-column prop="buyTime" label="购买时间" width="95" />

        <!-- 质保到期 -->
        <el-table-column prop="endTime" label="质保到期" width="95" />

        <!-- 登记信息 -->
        <el-table-column prop="address" show-overflow-tooltip label="登记信息" min-width="140">
          <template #default="scope">
            {{ scope.row.userName }}&nbsp;{{ scope.row.userPhone }}&nbsp;
            <span v-if="scope.row.province">{{
              scope.row.province +
              scope.row.city +
              scope.row.area +
              scope.row.town +
              scope.row.address
            }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="50" :align="'center'" fixed="right">
          <template #default="{ row }">
            <h-link v-permission="'order_commodity'" @click="showDrawer(row)">修改</h-link>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 12px; display: flex; justify-content: flex-end">
        <el-pagination
          v-model:current-page="getGoodListPagination.page"
          layout="total, prev, pager, next, jumper"
          :total="goodListTotal"
          background
          :page-size="4"
          @current-change="getGoodList"
        />
      </div>
    </div>

    <h-drawer
      v-model="updateProductDrawerVisible"
      :loading="changeLoading || queryLoading || updateLoading"
      title="修改产品信息"
      :width="600"
      unit="px"
      @close="hideUpdateGoodDrawer"
    >
      <el-form
        v-if="updatingProduct"
        label-position="top"
        :model="updatingProduct"
        class="modal_form_content"
      >
        <el-form-item label="新条码查询">
          <div style="display: flex; width: 100%; column-gap: 12px">
            <el-input
              v-model.trim="querySnCode"
              placeholder="请输入条码"
              @keyup.enter="onQuerySnCode"
            />
            <h-button type="primary" @click="onQuerySnCode">搜索</h-button>
          </div>
        </el-form-item>
        <el-form-item label="产品信息">
          <el-input
            readonly
            type="textarea"
            :autosize="{ minRows: 1, maxRows: 16 }"
            :value="
              [
                updatingProduct.goodsCode || '',
                updatingProduct.goodsBrand || '',
                updatingProduct.goodsName || '',
                updatingProduct.goodsModel || '',
                updatingProduct.goodsSpec,
              ]
                .filter((o) => o)
                .join('  ')
            "
          />
        </el-form-item>
        <el-form-item label="销售型号" class="mt10">
          <el-input readonly :value="updatingProduct.saleModels" />
        </el-form-item>
        <el-form-item label="产品数量" class="mt10">
          <el-input readonly :value="updatingProduct.qty" />
        </el-form-item>
        <el-form-item label="购买时间" class="mt10">
          <el-input readonly :value="updatingProduct.buyTime" />
        </el-form-item>
        <el-form-item label="质保到期" class="mt10">
          <el-input readonly :value="updatingProduct.endTime" />
        </el-form-item>
        <el-form-item label="登记信息" class="mt10">
          <el-input
            :value="
              updatingProduct.userName
                ? updatingProduct.userName ||
                  '' + ' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ' + updatingProduct.userPhone ||
                  '' + '\r\n' + updatingProduct.province ||
                  '' + '&nbsp;' + updatingProduct.city ||
                  '' + '&nbsp;' + updatingProduct.area ||
                  '' + '&nbsp; ' + updatingProduct.address ||
                  ''
                : ''
            "
            readonly
            type="textarea"
            :autosize="{ minRows: 1, maxRows: 16 }"
          />
        </el-form-item>
        <el-form-item label="资产码">
          <el-input :model-value="updatingProductRegisterCode" readonly />
        </el-form-item>
        <el-form-item label="条码" class="mt10 sn-code">
          <el-input :model-value="snCodes" readonly />
        </el-form-item>
      </el-form>
      <template #footer>
        <HButton is-modal type="primary" @click="onSave">保存修改</HButton>
        <HButton is-modal @click="hideUpdateGoodDrawer">取消</HButton>
      </template>
    </h-drawer>

    <create-code-modal
      ref="createCodeModalInstance"
      v-model="createCodeModalVisible"
      @update="onQuerySnCode"
    />
  </div>
</template>

<style scoped lang="scss">
  .order-detail-good-list {
    background-color: #fff;
    padding: 16px;
    display: flex;
    flex-direction: column;
    row-gap: 12px;

    .title {
      font-size: 14px;
      font-weight: bold;
      padding-left: 6px;
      border-left: 3px solid #007cff;
      display: flex;
      align-items: center;
      column-gap: 4px;
    }
  }

  .pro_dra {
    :deep(.el-form-item) {
      margin-bottom: 20px !important;
    }
  }

  .ord_dis {
    display: flex;
    align-items: center;
    gap: 5px;
    justify-content: center;

    .img {
      width: 12px;
      height: 12px;
      cursor: pointer;
    }
  }

  .modal_form_content {
    height: 100%;
    padding: 0 48px;

    .sn-code {
      flex: 1;
      display: flex;
      flex-direction: column;

      :deep(.el-form-item__content) {
        flex: 1;

        .el-textarea {
          height: 100%;

          .el-textarea__inner {
            height: calc(100% - 32px) !important;
          }
        }
      }
    }
  }
</style>
